package co.yixiang.modules.security.security.provider;

import co.yixiang.modules.security.service.UserLoginService;
import co.yixiang.modules.system.domain.User;
import co.yixiang.modules.user.domain.YxUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @Description:
 * @Author: liu
 * @Create: 2023-12-26
 */

@Component
@Slf4j
public class UserAuthenticationProvider implements AuthenticationProvider {
    /**
     * 自定义MD5 加密
     */
    @Autowired
    private PasswordEncoder userPasswordEncoder;

    @Autowired
    private UserLoginService userService;

    /**
     * 自定义验证方式
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取用户输入的用户名和密码
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        //通过获取的用户名，得到userDetails对象
        UserDetails user = userService.loadUserByUsername(username);
        //加密过程在这里体现，明文，密文
        if (!userPasswordEncoder.matches(password, user.getPassword())) {
            throw new UsernameNotFoundException("账号密码错误");
        }
//        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(user, password, null);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }
}
